// pages/order/order.js

import {
    getbaseUrl,
    requestUtil
} from "../../utils/request"

import {getFloatStr} from "../../utils/util"

Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 评论数量
        leiHei:0,
        commentList:[
            {
                img:"xx.jpg",
                userName:"1****59",
                date:"2022-11-26",
                rateContent:" 无敌好吃的热辣辣冰淇淋，超级脆，一口咬下去咔咔咔的，汁水也是多多的，特别满足",
                conentImg:"p1.png"
            },
            {
                img:"p2.png",
                userName:"1****34",
                date:"2022-10-26",
                rateContent:" 可以，开会员优惠很大，奶茶喝起来不错",
                conentImg:"p4.png"
            },
            {
                img:"mdl.jpeg",
                userName:"18****4",
                date:"2022-10-23",
                rateContent:" 不错，还是挺好喝的",
                conentImg:"p3.png"
            },
            {
                img:"1662468390344.jpg",
                userName:"m**de",
                date:"2022-10-23",
                rateContent:"店家老板娘狠不戳，人美心善，爱了爱了",
                conentImg:"p2.png"
            },

            {
                img:"p3.png",
                userName:"m**de",
                date:"2022-10-23",
                rateContent:"店家狠不戳，美心善，爱了",
            },

            {
                img:"p2.png",
                userName:"m**de",
                date:"2022-10-23",
                rateContent:"店家老板娘狠不戳，人美心善，爱了爱了",
            },
            {
                img:"p1.png",
                userName:"m**de",
                date:"2022-10-23",
                rateContent:"老板娘狠不戳，人美心善，爱了爱了",
            },
        ],

        isShopScroll:false,
        topBarTop:0,
        hei:0,
        container:null,
        statusBarHeight: 0,//状态栏的高度
        navheight: 0,//胶囊的高度
        pagetop: 0,//状态栏的高度+胶囊的高度
        pagetopY:0,
        scrollTop: 0,//页面滚动的值
        numop: 0,
        scrollheight: 0,
        // 商店的名字
        shopname: '',
        // 店铺的距离
        distance: '',
        // 店铺的图像
        storeImg:'',
        //店铺的id
        storeId: 0,
        //店铺的地址
        storeaddress: '',
        show: false,
        speci: [{
                name: "1磅(454g)-2-3人食",
                type: 1
            },
            {
                name: "2磅(908g)-4-7人食",
                type: 2
            },
            {
                name: "3磅(1.36kg)-8-12人食",
                type: 3
            },
            {
                name: "5磅(2.27kg)-12-人食",
                type: 4
            }
        ],
        speciActive: 0,
        // 规格的类型
        type: 1,
        // 商品标题
        shopTitle: [],
        // 基础路径
        baseUrl: '',
        // 商品标题高亮
        shopTitleActive: 0,
        //商品内容
        shopContent: [],
        // 弹出框的商品内容,
        popupShop: {},
        // 商品内容的标题
        shopContentTitle: 'yao0',
        currindex: 0,
        heightArr: [],
        // 用户的信息
        userInfo: {},
        // 用户信息token
        token: "",

        // 用户的密码
        isPayPassword:0,
        //购物车列表
        shop: {
            // 购物车列表显示隐藏
            cartShow: false,
            cartList: [],
            totalPrice: 0,
            listLength: 0,
            shopContent: [],

            // 屏幕的可用高度
            screenH: 0
        },
        // 节流阀
        throttle: false,
        popThrottle:null,

        // 点餐active
        activeOrder:1
    },
    // 改变商品标题

    
    changeTitle(e) {
        // console.log(e.currentTarget.dataset.index)
        wx.pageScrollTo({
            scrollTop:this.data.topBarTop+15,
            // duration: ,
          })
        this.setData({
            isShopScroll:true
        })
        // console.log(this.data.topBarTop)
       
        const index = e.currentTarget.dataset.index
        this.setData({
            shopTitleActive: index,
            shopContentTitle: "yao" + index
        })

    },

    // 用户登录

    // userLogin() {
    //     console.log("yaohf")
    //     wx.getUserProfile({
    //         desc: "我点",
    //         lang: "zh_CN",
    //         success: (res) => {
    //               console.log(res.userInfo)
    //             let {
    //                 avatarUrl,
    //                 nickName,
    //                 gender
    //             } = res.userInfo
    //             wx.login({
    //                 success: (res) => {
    //                     console.log(res)
    //                     let p = requestUtil({
    //                         url: "/my/emitUserPid",
    //                         method: "get",
    //                         header: {
    //                             'content-type': 'application/x-www-form-urlencoded'
    //                         },
    //                         data: {
    //                             code: res.code,
    //                             avatarUrl,
    //                             nickName,
    //                             gender
    //                         },

    //                     })
    //                     p.then(({
    //                         data
    //                     }) => {
    //                            console.log(data.data)
    //                         wx.setStorage({
    //                             key: "userInfo",
    //                             data: JSON.stringify(data.data),
    //                             success: () => {
    //                                 this.getUserInfo()
    //                             }
    //                         })
    //                     })
    //                 },
    //                 fail: (err) => {
    //                     console.log(err)
    //                 }
    //             })
    //         }


    //     })
    // },



    // 加入购物车
    addCart() {
    
        clearTimeout(this.data.popThrottle)
        this.data.popThrottle = setTimeout(()=>{
            // console.log("4343")

        
        if (!this.data.userInfo.token) {
            console.log(!this.data.userInfo.token)
            wx.navigateTo({
              url: '/pages/login/login',
            })
            // if()
            return
        }
        // console.log("我是后来的")
      
        let shopObj = {
            ...this.data.popupShop,
            storeId: this.data.storeId,
            num: 1,
            isShow: 1,
            speci: this.data.type,
            price: this.data.popupShop.price + this.data.type * 10 - 10,
            openId: this.data.userInfo.openid
        }

        let index = this.data.shop.cartList.findIndex(item => {
            return item.cat_id == shopObj.cat_id
        })

        if (index >= 0) {
            let num = ++this.data.shop.cartList[index].num
            let id = this.data.shop.cartList[index].id
            let openId = shopObj.openId
            // 购物车中有，更改购物车的数量
            this.setCartNum({
                num: num,
                id: id,
                openId

            })
            // console.log(index,++this.data.shop.cartList[index].num,this.data.shop.cartList[index].id)
          
        } else {
            // 购物车中没有加入购物车
            this.pushShopData(shopObj)
         
        }

        },200)
            
        // this.onClose()
      
        //关闭弹出层
        this.onClose()
    },

    // 减商品
    showShop(e) {

        // console.log(e.currentTarget.dataset.shopcatid)
        let cat_id = e.currentTarget.dataset.shopcatid
        let index = this.data.shop.cartList.findIndex(item => {
            return item.cat_id == cat_id
        })

        // 商品的数量
        let num = --this.data.shop.cartList[index].num
        let id = this.data.shop.cartList[index].id
        let openId = this.data.userInfo.openid
        if (num < 1) {
            this.data.shop.cartList.splice(index, 1)
            // console.log("数量小于0了，不能再减了")
            this.deleteShop(id, openId)
            return
        }

        this.setCartNum({
            id,
            num,
            openId

        })


    },
    //发请求，删除购物车中的商品
    deleteShop(id, openId) {
        // console.log(id)
        let res = requestUtil({
            url: '/shop/deleteCartShop',
            method: 'get',
            data: {
                id,
                openId
            }
        })
        res.then(({
            data
        }) => {
            if (data.status == 200) {

                this.getCartList()
            }
        })
    },

    //发请求，修改购物车中的数量
    setCartNum(data) {
        let res = requestUtil({
            url: '/shop/setShopNum',
            method: 'get',
            data: data
        })
        res.then(({
            data
        }) => {
            if (data.status == 200) {
                this.getCartList()
            }
            // console.log(data.status==200)
        })
    },

    //发请求，把商品数据添加到数据库购物车当中
    pushShopData(item) {
     

        let res = requestUtil({
            url: "/shop/pushCartList",
            data: item,
            method: "get"
        })
        res.then(r => {
            if (r.data.status == 200) {
                this.getCartList()
            }
        })
   
    },

    //购物车列表的操作
    // 减少商品

    reduce(e) {
        this.showShop(e)
        // console.log(this.data.shop.cartList.length)

        if (this.data.shop.cartList.length == 0) {
            this.onCartClose()
        }
       
    },

    // 增加商品
    add(e) {

        let openId = this.data.userInfo.openid
        let {
            id,
            num
        } = e.currentTarget.dataset
        let a = ++num
        this.setCartNum({
            id,
            num: a,
            openId
        })
        // this.setCartNum()
      
    },

    //清除购物车
    clear() {
        let storeId = this.data.storeId
        let openId = this.data.userInfo.openid
        let res = requestUtil({
            url: '/shop/clearCart',
            data: {
                storeId,
                openId
            }
        })
        res.then(({
            data
        }) => {
            if (data.status == 200) {
                this.getCartList()
                this.onCartClose()
            }
        })
      
    },

    //展示购物车商品
    toShopList() {
        // console.log("ijflesjkfes")
        if (this.data.shop.cartList == 0) return
        this.setData({
            "shop.cartShow": !this.data.shop.cartShow
        })

    },
    //隐藏购物车商品
    onCartClose() {
        this.setData({
            "shop.cartShow": false
        })
    },



    // 去支付
    toPayment() {
     
        if (this.data.shop.listLength == 0) return
        let storeId = this.data.storeId
        let openId = this.data.userInfo.openid
        // 商店的名字
        let shopname = this.data.shopname
        // 店铺的距离
        let distance = this.data.distance
        // 店铺的地址
        let storeaddress = this.data.storeaddress
        this.onCartClose()
        wx.navigateTo({
            url: `/pages/payment/payment?shopname=${shopname}&distance=${distance}&storeId=${storeId}&storeaddress=${storeaddress}&openId=${openId}`,
        })
    },

    cao(){
        // console.log("fefs")
    },

    // 改变规格的样式
    changeActive(e) {
        // console.log(e.currentTarget.dataset)
        let index = e.currentTarget.dataset.index
        let type = e.currentTarget.dataset.type
        this.setData({
            speciActive: index,
            type: type,
            "popupShop.speci": type
        })
    },
    // 展示弹出层
    showPopup(e) {

        const {
            info,
            name
        } = e.currentTarget.dataset
        this.setData({
            show: true,
            popupShop: info,
            shopName: name
        })

        // console.log(e.currentTarget.dataset)

    },


    // 关闭弹出层
    onClose() {
        this.setData({
            show: false,
            speciActive: 0,
            type: 1,
        })
    },

    // 获取商品的标题
    getShopTitle() {
        let p = requestUtil({
            url: '/shop/getShopTitle',
            method: 'get'
        })
        p.then(res => {
            //   console.log(res.data.data)
            this.setData({
                shopTitle: res.data.data,
                baseUrl: getbaseUrl() + "/image/"
            })
        })
    },
    // 获取商品内容
    getShop() {
        // console.log(this.data.storeId)
        let storeId = this.data.storeId
        let openId = this.data.userInfo.openid

        let p = requestUtil({
            url: '/shop/getShop',
            method: 'get',
            data:{
                storeId,
                openId
            }
        })
        p.then((res) => {
         
            if(res.data.status==200){
                 this.setData({
                    shopContent: res.data.data,
                })
                if (this.data.heightArr.length == 0) {
                    this.getRectInfo()
                }
                wx.hideLoading()
            }else{
                this.setData({
                    shopContent: [],
                })
                wx.hideLoading()
            }
          
            // this.getRectInfo()

        })
    },



    // 获取与顶部之间的距离
    getRectInfo() {
        // console.log("fefse")
        let heightArr = [];
        let h = 0;

        const query = wx.createSelectorQuery();

        query.selectAll('.pro-box').boundingClientRect()
        query.exec((res) => {
            // console.log(res)
            // res就是 所有标签类名为pro-box元素的数组
            res[0].forEach((item) => {
              
                h = item.top -444-38;
                // console.log(h)
                heightArr.push(h);
            })
            this.setData({
                "heightArr": heightArr,
                //   "scrollVal": heightArr[this.data.currindex - 1],
            })

            // 算出每块区域到达的高度
            // console.log('heightArr', heightArr) //  [210, 800, 1390]
        })

    },

    onPageScroll1(e){
        // console.log(e.detail.scrollTop)
        this.setData({
            scrollTop:e.detail.scrollTop
        })
    },

    onPageScroll(e){
        // console.log(e.scrollTop>this.data.topBarTop)
        // console.log(e.scrollTop,this.data.topBarTop)
        if(e.scrollTop>this.data.topBarTop){
            this.setData({
                isShopScroll:true
            })
        }else{
            this.setData({
                isShopScroll:false
            })
        }
       
        this.setData({
            scrollTop:e.scrollTop
        })
    },

    // 获取置顶元素的标签
    getBarHei(){
        // let yaohei=0
        wx.getSystemInfo({
            success: (result) => {
              // console.log(result)
              if (result.model == "iPhone 5" || result.model == "iPhone SE (2nd generation)<iPhone12,8>") {
                            const query = wx.createSelectorQuery();
                    query.selectAll(".topBar").boundingClientRect()
                    query.exec((res)=>{
                        // console.log(res[0][0])
                        // console.log(res[0][0].top+100)
                        this.setData({
                            topBarTop:res[0][0].top+70
                        })
                    })
              }else{
                const query = wx.createSelectorQuery();
                query.selectAll(".topBar").boundingClientRect()
                query.exec((res)=>{
                    // console.log(res[0][0])
                    // console.log(res[0][0].top+100)
                    this.setData({
                        topBarTop:res[0][0].top+75
                    })
                })
              }
      
            },
          })
 
    },

    onScroll(event) {
        // if(!this.isShopScroll){
        //     return
        // }
        // console.log(event.detail.scrollTop,this.data.heightArr)
        // console.log(this.data)
        // console.log(event.detail.scrollTop)
        if (event.detail.scrollTop < this.data.heightArr[1]-20) {
            // console.log("fefs")
            this.setData({
                shopTitleActive: 0
            })
        } else if (event.detail.scrollTop < this.data.heightArr[2]-20) {
            this.setData({
                shopTitleActive: 1
            })
        } else if (event.detail.scrollTop < this.data.heightArr[3]-20) {
            this.setData({
                shopTitleActive: 2
            })
        }else if (event.detail.scrollTop < this.data.heightArr[4]-20) {
            this.setData({
                shopTitleActive: 3
            })
        }
        else if (event.detail.scrollTop > this.data.heightArr[4]-20) {
            this.setData({
                shopTitleActive: 4
            })
        }


        //     if(event.detail.scrollTop>=344){
        //         console.log(event.detail.scrollTop)    
        //         // console.log(event) 
        //     }
        //    console.log(this.data.heightArr)
    },

    // 改变点餐的active
    changeOdActive(e){
        // console.log(e.currentTarget.dataset.id)
        let id =e.currentTarget.dataset.id
        this.setData({
            activeOrder:id
        })
    },

    // 计算购物车里面的价格和数量
    calculate(data) {
        // if (data.length == 0) 
        let totalPrice = data.reduce((total, current) => {
            return total += current.price * current.num
        }, 0)

        let shoplen = data.length

        this.setData({
            "shop.totalPrice": totalPrice.toFixed(2),
            "shop.listLength": shoplen
        })
    },
    goBack(){
        wx.navigateBack({
          delta: 1,
        })
    },

    moveHandle () {},
    // 获取商店对应的购物车数据
    
    getCartList() {
        let storeId = this.data.storeId
        let openId = this.data.userInfo.openid
        let r = requestUtil({
            url: '/shop/getCartList',
            method: 'get',
            data: {
                storeId: storeId,
                openId
            }
        })

        r.then(({
            data
        }) => {
            if (data.status == 200) {
                // console.log(data.data)
                // console.log("2222")
                this.calculate(data.data)

                this.setData({
                    "shop.cartList": data.data
                })

                //对比购物车和商品数据，生成一个商品的数据
                // this.generateShopDat(data.data)

            } else {
                console.log("获取商品失败")
            }
            this.getShop()
        }), (e) => {
            console.log(e)
        }
     
    },

    // 获取本地的用户信息

    getUserInfo() {
        wx.getStorage({
            key: "userInfo",
            success: (res) => {
                // res.data
                // console.log(res.data)
                this.setData({
                    userInfo: JSON.parse(res.data)
                })
            }

        })
    },

    // 获取屏幕可用高度
    getHei(){
        wx.getSystemInfo({
          success: (result) => {
            //   console.log(result.windowHeight)
              this.setData({
                  hei:result.windowHeight
              })
          },
        })
    },

    // 获取用户评论的数量
    commentList(){
        this.setData({
            leiHei:this.data.commentList.length
        })
    },

    // 获取评论本地数据
    getStoreCommentList(shopId){
        wx.getStorage({
            key:shopId,
            success:({data})=>{
                this.data.commentList.push(...JSON.parse(data))
                this.setData({
                    commentList:this.data.commentList.reverse()
                })
                this.commentList()
            },
            fail:()=>{
                this.commentList()
            }
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // this.commentList()
        wx.showLoading({
            title: '数据加载中',
          })
          this.getBarHei()
          this.getHei()
          this.setData({
            //    状态栏的高度
            statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'] + 'px',
            //    胶囊的高度 也就是自定导航栏的高度
            navheight: wx.getMenuButtonBoundingClientRect()['height'] + 'px',
            //    状态栏加导航栏的高度 加上下的padding的高度 12
            pagetop: wx.getMenuButtonBoundingClientRect()['height'] + wx.getSystemInfoSync()['statusBarHeight'] + 12 + 'px',
        })
        wx.getSystemInfo({
            success: (result) => {
                if (result.model == "iPhone 5" || result.model == "iPhone SE (2nd generation)<iPhone12,8>") {
                   let  pagetopY= wx.getMenuButtonBoundingClientRect()['height'] + wx.getSystemInfoSync()['statusBarHeight']
                    this.setData({
                        pagetopY:pagetopY-8
                    })
                }else{
                    let pagetopY= wx.getMenuButtonBoundingClientRect()['height'] + wx.getSystemInfoSync()['statusBarHeight']
                    this.setData({
                        pagetopY:pagetopY
                    })
                }
               
            },
          })

          

        this.getUserInfo()
        // console.log(options)
        // console.log("只渲染一次")
        if (options) {
            let {
                distance,
                shopname,
                storeId,
                storeaddress,
                storeImg
            } = options
            this.getStoreCommentList(storeId)
            this.setData({
                distance: distance,
                shopname: shopname,
                storeId: storeId,
                storeaddress: storeaddress,
                storeImg:storeImg
            })
            // 获取购物车的数据
            setTimeout(()=>{
                this.getCartList()
            },100)
  
        }


        // this.getShop()
        // this.getCartList()
        this.getShopTitle()

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        let query = wx.createSelectorQuery();
        query.select('.shop-title').boundingClientRect(rect => {
            //获取到元素
            let res = wx.getSystemInfoSync()
            // console.log(res,'a')
            let height = res.windowHeight - rect.height - 48;
            // 屏幕可用的高度
            // console.log(res.windowHeight)
            let winHeight = res.windowHeight / 2 + 50+87
            this.setData({
                scrollheight: height+90+40,
                "shop.screenH": winHeight
            })

        }).exec();



    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getUserInfo()
        // console.log(this.data.storeId)
        // console.log("fesfse")
        if(this.data.storeId){
            this.getCartList()
        }
        // setTimeout(() => {
        //     this.getShop()
        // })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        this.setData({
          
            heightArr:[]
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})